<template>
  <div class="nav-container">
    <el-menu
      :default-active="activeIndex"
      class="nav-menu"
      mode="horizontal"
      router
    >
      <el-menu-item index="/">首页</el-menu-item>
      <el-menu-item index="/emergency">应急信息</el-menu-item>
      <el-menu-item index="/hotels">酒店预订</el-menu-item>
      <el-menu-item index="/entertainment">餐饮娱乐</el-menu-item>
      <el-menu-item index="/weather">天气信息</el-menu-item>

      <!-- 用户菜单 -->
      <el-submenu index="user" class="user-menu">
        <template slot="title">
          欢迎, {{ username }}
        </template>
        <!-- 管理员菜单项 -->
        <template v-if="isAdmin">
          <el-menu-item index="/admin/emergency">应急信息管理</el-menu-item>
          <el-menu-item index="/admin/hotel">酒店管理</el-menu-item>
          <el-menu-item index="/admin/entertainment">餐饮娱乐管理</el-menu-item>
          <el-divider></el-divider>
        </template>
        <el-menu-item index="/profile">个人中心</el-menu-item>
        <el-menu-item @click="handleLogout">退出登录</el-menu-item>
      </el-submenu>
    </el-menu>
  </div>
</template>

<script>
export default {
  name: 'NavBar',
  data() {
    return {
      activeIndex: '/',
      username: '',
      isAdmin: false
    }
  },
  created() {
    this.initUserInfo()
  },
  methods: {
    initUserInfo() {
      const userStr = localStorage.getItem('user')
      if (userStr) {
        try {
          const user = JSON.parse(userStr)
          this.username = user.username
          this.isAdmin = user.role === 'admin'
          console.log('NavBar user info:', user)
        } catch (e) {
          console.error('Failed to parse user info:', e)
          // 如果解析失败，清除可能损坏的数据
          localStorage.removeItem('user')
          localStorage.removeItem('token')
        }
      }
    },
    handleLogout() {
      localStorage.removeItem('token')
      localStorage.removeItem('user')
      this.$router.push('/login')
      this.$message.success('退出登录成功')
    }
  },
  watch: {
    '$route'(to) {
      this.activeIndex = to.path
    }
  }
}
</script>

<style scoped>
.nav-container {
  border-bottom: 1px solid #e6e6e6;
}

.nav-menu {
  display: flex;
  align-items: center;
  padding: 0 20px;
}

.user-menu {
  margin-left: auto;
}

:deep(.el-submenu__title) {
  display: flex;
  align-items: center;
}

:deep(.el-submenu__icon-arrow) {
  margin-top: 0;
}

:deep(.el-divider--horizontal) {
  margin: 5px 0;
}
</style> 